package com.kreateinfinity.msdi.web.authentication;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.kreateinfinity.msdi.model.authentication.User;
import com.kreateinfinity.msdi.service.authentication.UserAuthenticationService;
@SuppressWarnings("deprecation")
@Controller
public class LoginFormController extends SimpleFormController {
	private static Logger LOGGER = Logger.getLogger(LoginFormController.class); 

	@Autowired
	private UserAuthenticationService userAuthenticationService;

	/***/


	public LoginFormController(){
		super();
		System.out.println("test point 0");
		setCommandClass(LoginFormData.class);
		setCommandName("loginData");
		LoginFormvalidator loginFormValidator = new LoginFormvalidator();
		setValidator(loginFormValidator);

	}

	/**
	 * @return the userAuthenticationService
	 */
	public UserAuthenticationService getUserAuthenticationService() {
		return userAuthenticationService;
	}

	@Override
	@RequestMapping(value="/login.html", method=RequestMethod.POST)
	public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		LOGGER.debug("is invoked");
		LOGGER.debug("test point 1");
		LoginFormData formData = (LoginFormData)command;
		LOGGER.debug("test point 2");
		User user = userAuthenticationService.getLogin(formData.getUsername(), formData.getPassword());
		if (user == null) {
			LOGGER.debug("test point 10");
			errors.addError(new ObjectError("globalErrors","Invalid Username/Password"));

			return showForm(request,response,errors);
		}

		request.getSession().setAttribute("user", user);
		request.setAttribute("headerTab", "basic");
		ModelAndView modelAndView = new ModelAndView("home");
		return modelAndView;
	}

	/**
	 * @param userAuthenticationService the userAuthenticationService to set
	 */
	public void setUserAuthenticationService(
			UserAuthenticationService userAuthenticationService) {
		this.userAuthenticationService = userAuthenticationService;
	}
}
